<template>
  <div>
    <div>
      <h1>商品列表</h1>
    </div>
    <div>
      <el-button type="primary" @click="handleAddProd">添加商品</el-button>
      <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
    </div>
    <div>
      <el-table
        :data="prodList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="ID" />
        <el-table-column prop="prodSpu" label="SPU" />
        <el-table-column prop="prodName" label="名称" />
        <el-table-column prop="typeName" label="类型" />
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="tagName" label="标签" />
        <el-table-column prop="apprName" label="供应商" />
        <el-table-column label="图片">
          <template #default="scope">
            <el-image
              v-if="scope.row.prodImage != null"
              :src="scope.row.prodImage"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="prodStatus" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.prodStatus == 0" type="">未上架</el-tag>
            <el-tag v-if="scope.row.prodStatus == 1" type="success"
              >已上架</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="kindName" label="种类" />
        <el-table-column prop="createTime" label="时间" />
        <el-table-column label="操作" />
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
        <el-form :model="form">
          <el-form-item label="商品类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.kindId">
              <el-radio :value="0">实物商品</el-radio>
              <el-radio :value="1">虚拟商品</el-radio>
              <el-radio :value="2">卡密/网盘</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品分类" :label-width="formLabelWidth">
            <el-tree-select
              v-model="form.typeId"
              :data="typeListTree"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="商品名称" :label-width="formLabelWidth">
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品SPU" :label-width="formLabelWidth">
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品品牌" :label-width="formLabelWidth">
            <el-select v-model="form.brandId" placeholder="请选择品牌">
              <el-option
                v-for="item in brandListAll"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth">
            <el-select v-model="form.unitId" placeholder="请选择单位">
              <el-option
                v-for="item in unitListAll"
                :label="item.unitName"
                :value="item.unitId"
                :key="item.unitId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" :label-width="formLabelWidth">
            <el-select v-model="form.tagId" placeholder="请选择标签">
              <el-option
                v-for="item in tagListAll"
                :label="item.tagName"
                :value="item.tagId"
                :key="item.tagId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" :label-width="formLabelWidth">
            <el-select v-model="form.apprId" placeholder="请选择供应商">
              <el-option
                v-for="item in apprListAll"
                :label="item.apprName"
                :value="item.apprId"
                :key="item.apprId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品缩略图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/index/updateLoad"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmitAdd"> 提交 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getProdList,
  addProd,
  getTypeSelectTree,
  getBrandListAll,
  getUnitListAll,
  getTagListAll,
  getApprListAll,
  deleteProdAll,
} from "@/api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, type UploadProps, ElMessageBox } from "element-plus";

const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log("multipleSelection", multipleSelection.value);
};

const handleDeleteAll = () => {
  console.log("handleDeleteAll", multipleSelection.value);
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的商品");
    return;
  }
  ElMessageBox.confirm("您确定有删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProdAll(multipleSelection.value).then((res: any) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
  deleteProdAll;
};

const imageUrl = ref("");
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  imageUrl.value = response.data;
  form.value.prodImage = imageUrl.value;
};

const headers = {
  token: sessionStorage.getItem("token"),
};

const onSubmitAdd = () => {
  addProd(form.value).then((res: any) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const prodList = ref([]);
const brandListAll = ref([]);
const unitListAll = ref([]);
const tagListAll = ref([]);
const apprListAll = ref([]);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
});
const total = ref(0);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = ref({
  apprId: null,
  brandId: null,
  createBy: null,
  createTime: null,
  kindId: null,
  prodId: null,
  prodImage: null,
  prodName: "",
  prodSpu: "",
  prodStatus: null,
  tagId: null,
  typeId: null,
  unitId: null,
  updateBy: null,
  updateTime: null,
});

const typeListTree = ref([]);

const resetForm = () => {
  form.value = {
    apprId: null,
    brandId: null,
    createBy: null,
    createTime: null,
    kindId: null,
    prodId: null,
    prodImage: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    tagId: null,
    typeId: null,
    unitId: null,
    updateBy: null,
    updateTime: null,
  };
  imageUrl.value = "";
};

const handleAddProd = () => {
  console.log("添加商品");
  resetForm();
  dialogFormVisible.value = true;
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

const loadList = () => {
  getProdList(searchForm.value).then((res: any) => {
    if (res.data.code == 200) {
      prodList.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadList();
  getTypeSelectTree().then((res: any) => {
    if (res.data.code == 200) {
      typeListTree.value = res.data.data;
    }
  });

  getBrandListAll().then((res: any) => {
    if (res.data.code == 200) {
      brandListAll.value = res.data.data;
    }
  });

  getUnitListAll().then((res: any) => {
    if (res.data.code == 200) {
      unitListAll.value = res.data.data;
    }
  });

  getTagListAll().then((res: any) => {
    if (res.data.code == 200) {
      tagListAll.value = res.data.data;
    }
  });

  getApprListAll().then((res: any) => {
    if (res.data.code == 200) {
      apprListAll.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>